package handler

import (
	"encoding/json"
	"github.com/sirupsen/logrus"
	"gofile/src/config"
	"gofile/src/util"
	"io"
	"io/ioutil"
	"net/http"
	"os"
	"path/filepath"
	"strings"
)

type CopyFileReq struct {
	SrcPaths []string `json:"src_paths"`
	DistPath string   `json:"dist_path"`
}

func moveFileOrDir(srcList []string, distDir string) error {
	for _, src := range srcList {
		// Get the file info
		fileInfo, err := os.Stat(src)
		if err != nil {
			return err
		}
		// Check if the file is a directory
		if fileInfo.IsDir() {
			// Create the destination directory
			err = os.MkdirAll(filepath.Join(distDir, filepath.Base(src)), os.ModePerm)
			if err != nil {
				return err
			}
			// Get the list of files in the source directory
			files, err := ioutil.ReadDir(src)
			if err != nil {
				return err
			}
			// Recursively move the files in the source directory to the destination directory
			var srcList []string
			for _, file := range files {
				srcList = append(srcList, filepath.Join(src, file.Name()))
			}
			err = moveFileOrDir(srcList, filepath.Join(distDir, filepath.Base(src)))
			if err != nil {
				return err
			}
			// Remove the source file
			err = os.Remove(src)
			if err != nil {
				return err
			}
		} else {
			// Open the source file
			srcFile, err := os.Open(src)
			if err != nil {
				return err
			}
			defer srcFile.Close()
			// Create the destination file
			distFile, err := os.Create(filepath.Join(distDir, filepath.Base(src)))
			if err != nil {
				return err
			}
			defer distFile.Close()
			// Copy the contents of the source file to the destination file
			_, err = io.Copy(distFile, srcFile)
			if err != nil {
				return err
			}
			// Remove the source file
			err = os.Remove(src)
			if err != nil {
				return err
			}
		}
	}
	return nil
}

func MoveFileHandler(w http.ResponseWriter, r *http.Request) {
	body, _ := io.ReadAll(r.Body)

	logrus.Infoln(body)
	var copyFileReq CopyFileReq
	err := json.Unmarshal(body, &copyFileReq)
	if err != nil {
		util.ProcessResult("参数错误", err, w)
		return
	}
	src := copyFileReq.SrcPaths
	dist := copyFileReq.DistPath
	myCfg := config.GetConfig()
	var srcPath []string
	for _, s := range src {
		srcPath = append(srcPath, s)
	}
	distPath := myCfg.File.Dir + dist

	// call deleteFileOrDir with the path of the file to be deleted
	err = moveFileOrDir(srcPath, distPath)
	// Convert src to string
	srcString := strings.Join(src, ",")
	if err != nil {
		// handle error
		util.ProcessResult("复制文件"+srcString+"到失败", err, w)
	} else {
		// file/directory deleted successfully
		util.ProcessResult("复制文件"+srcString+"到成功", nil, w)
	}
}
